package com.axis2.common.util;

import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.axis2.transport.http.HTTPConstants;

import javax.xml.namespace.QName;

/**
 * @ClassName: WsCommunication
 * @Description: webservice客户端
 * @author Fred
 * @date 2013-3-21 下午3:37:23
 * 
 */
public class WsCommunication {

	private static RPCServiceClient rpcServiceClient = null;
	/**	
	 * @Description: 通道ws调用
	 * @param  url
	 * @param  method
	 * @param  reqxml
	 * @param @throws Exception    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public static String channelInvoke(String url,String method,String reqxml) throws Exception {
		return wsInvoke(url,method,"http://com.ips.core.channel",reqxml);
	}

	/**
	 * @Description: 普通ws调用
	 * @param url
	 * @param method
	 * @param reqxml
	 * @param @throws Exception 设定文件
	 * @return String 返回类型
	 * @throws
	 */
	public static String wsInvoke(String url, String method, String nameSpace, String reqxml) throws Exception {
		return invoke(url, method, nameSpace, new Object[] { reqxml }, new Class[] { String.class });
	}

	/**
	 * @Description: ws调用
	 * @param url
	 * @param method
	 * @param nameSpace
	 * @param params
	 * @param paramTyps
	 * @param @throws Exception 设定文件
	 * @return String 返回类型
	 * @throws
	 */
	@SuppressWarnings("rawtypes")
	public static String invoke(String url, String method, String nameSpace, Object[] params, Class[] paramTyps)
			throws Exception {
		String result = "";
		try {
			RPCServiceClient rpcServiceClient = getInstance();
			Options options = rpcServiceClient.getOptions();
			options.setCallTransportCleanup(true);
			EndpointReference targetEPR = new EndpointReference(url);
			options.setTo(targetEPR);
			options.setTimeOutInMilliSeconds(60000L);// 设置超时时间1分钟
			options.setAction(nameSpace + method);
			options.setProperty(HTTPConstants.CHUNKED, Boolean.FALSE);
			QName opAddEntry = new QName(nameSpace, method);
			Object[] opAddEntryArgs = params;
			Class[] classes = paramTyps;
			result = (String) rpcServiceClient.invokeBlocking(opAddEntry, opAddEntryArgs, classes)[0];
		} catch (Exception ex) {
			throw ex;
		}
		return result;
	}

	private  static RPCServiceClient getInstance() throws AxisFault {
		if (rpcServiceClient == null) {
			rpcServiceClient = new RPCServiceClient();
		}
		return rpcServiceClient;
	}
}
